package org.example.myleet.p811;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> domainCount = new HashMap<>();
        for (String log : cpdomains) {
            String[] logParts = log.split(" ");
            Integer count = Integer.parseInt(logParts[0]);
            String[] parts = logParts[1].split("\\.");
            String domain;
            if (parts.length == 3) {
                domain = String.format("%s.%s.%s", parts[0], parts[1], parts[2]);
                domainCount.put(domain, domainCount.getOrDefault(domain, 0) + count);
                domain = String.format("%s.%s", parts[1], parts[2]);
                domainCount.put(domain, domainCount.getOrDefault(domain, 0) + count);
                domain = parts[2];
                domainCount.put(domain, domainCount.getOrDefault(domain, 0) + count);
            }
            if (parts.length == 2) {
                domain = String.format("%s.%s", parts[0], parts[1]);
                domainCount.put(domain, domainCount.getOrDefault(domain, 0) + count);
                domain = parts[1];
                domainCount.put(domain, domainCount.getOrDefault(domain, 0) + count);
            }
            if (parts.length == 1) {
                domain = parts[0];
                domainCount.put(domain, domainCount.getOrDefault(domain, 0) + count);
            }
        }
        List<String> res = new ArrayList<>(domainCount.size());
        for (Map.Entry<String, Integer> entry : domainCount.entrySet()) {
            res.add(String.format("%d %s", entry.getValue(), entry.getKey()));
        }
        return res;
    }
}
